<template>
  <div>
    <el-table
      class="vul-table"
      ref="table"
      v-loading="loading && showLoading"
      v-bind="tableAttr"
      :data="list"
    >
      <template v-for="(column, index) in columns2">
        <el-table-column  v-bind="column">
          <template v-slot:default="scope">
            <span v-if="column.isReplace">
                   {{ column.obj[scope.row[column.prop]] || emptyText }}
            </span>
            <span v-else-if="column.isContentPart">
                <ShowCode :codeInfo=codeInfo(scope.row[column.prop])> </ShowCode>
            </span>
            <el-tooltip
                v-else
                popper-class="vul-table-tooltip"
                effect="dark"
                placement="top"
                :content="scope.row[column.prop] || emptyText">
              <p
                  class="over-flow"
                  :columns="columns"
              >
                <span>
                  {{ scope.row[column.prop] || emptyText }}
                </span>
              </p>
            </el-tooltip>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination
      ref="pager"
      v-if="showPager"
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      v-bind="pagerOptions"
      :current-page="pageNumber"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script lang="ts" setup>
import TableBtns from "./table-btns.vue";
import Render from "./render";
import ShowCode from "@/components/Expose/ShowCode.vue";
import {defineProps, ref,reactive,computed,nextTick,onMounted,defineEmits} from 'vue';
import {useStore} from 'vuex';
const emit=defineEmits(['loaded','sizeChange','currentChange']);
const store =useStore();
const props=defineProps({
  uri: {
      type: String,
      default: "",
    },
    showLoading: {
      type: Boolean,
      default: false,
    },
    columns: {
      type: Array,
      default: () => [],
    },
    params: {
      type: Object,
      default: () => ({}),
    },
    tableAttr: {
      type: Object as any,
      default: () => ({}),
    },
    showPager: {
      type: Boolean,
      default: true,
    },
    pagerAttr: {
      type: Object,
      default: () => ({}),
    },
    emptyText: {
      type: String,
      default: "-",
    },
})
const loading=ref(false);
const defaultColumnAttr=reactive({
  "show-overflow-tooltip": true,
});
const list=ref([]);
const total=ref(0);
const pageNumber=ref(1);
const pagerOptions=reactive({
  background: true,
        pageSizes: [5, 10, 20, 50, 100],
        pageSize: 10,
        layout: "total, sizes, prev, pager, next, jumper",
        ...props.pagerAttr,
});
const columns2=computed(()=>{
  let columns = props.columns;
      if (!columns) columns = [];
      return props.columns.map((el:any) => {
        el.render = filterRender(el);
        const colInfo = { ...defaultColumnAttr, ...el };
        return {
          ...colInfo,
          showOverflow: colInfo["show-overflow-tooltip"],
          "show-overflow-tooltip": false,
        };
      });
})
const expandRender=computed(()=>{
  let render = function () {
        return "";
      };
      for (let i = 0; i < props.columns.length; i++) {
        const column :any= props.columns[i];
        if (column.type && column.type === "expand") {
          if (column.render) render = column.render;
        }
      }
      return render;
})
onMounted(()=>{
  nextTick(reload);
})
const codeInfo=(row)=> {
      return {
        code: row,
        language: 'http',
      };
    }
    const reload=async()=> {
      if (!props.uri) return;
      loading.value = true;
      const { code, data } = await store.dispatch(props.uri, {
        ...props.params,
        pageNumber: pageNumber.value,
        pageSize:  pagerOptions.pageSize,
      });
      loading.value = false;
      if (code == 0) {
        list.value = data.list;
        total.value = data.total;
        if (!list.value.length && total.value && pageNumber.value != 1) {
          pageNumber.value = 1;
          reload();
        }
        emit("loaded", data);
      }
    }
  const filterRender = (column) => {  
  return (h, { row }) => {  
    if (column.renderText) {  
      if (column['show-overflow-tooltip'] === false) {  
        return h('span', column.renderText(row));  
      } else {  
        // 假设 el-tooltip 是一个已经注册的全局或局部组件  
        return h('el-tooltip', {  
          props: {  
            content: column.renderText(row),  
            // 您可以添加其他 el-tooltip 组件需要的 props  
          },  
        }, [  
          h('span', { class: 'item' }, column.renderText(row)),  
          // 如果有需要，可以在这里添加 tooltip 的触发器元素  
        ]);  
      }  
    } else if (column.mapper) {  
      // 假设 vul-text-tooltip 是一个已经注册的全局或局部组件  
      const content = column.mapper.hasOwnProperty(row[column.prop])  
        ? column.mapper[row[column.prop]]  
        : row[column.key];  
      const style = (column.mapperStyle && column.mapperStyle[row[column.prop]]) || {};  
      return h('vul-text-tooltip', {  
        style,  
        props: {  
          content,  
          // 您可以添加其他 vul-text-tooltip 组件需要的 props  
        },  
      });  
    } else if (column.renderBtns) {  
      // 假设 TableBtns 是一个已经注册的全局或局部组件  
      return h(TableBtns, {  
        props: {  
          row,  
          renderButtons: column.renderBtns,  
          column,  
        },  
      });  
    } else if (column.render) {  
      // 假设 column.render 是一个 render 函数  
      return column.render(h, { row });  
    }  
    // 默认情况，返回一些内容或什么都不返回  
    return h('span', 'No render function defined');  
  };  
};
   const handleSizeChange=(size)=> {
      pagerOptions.pageSize = size;
      emit("sizeChange", size);
      handleCurrentChange(1);
    }
   const handleCurrentChange=(page)=> {
      pageNumber.value = page;
      reload();
      emit("currentChange", page);
    }
</script>
<style scoped>
::v-deep .el-table__header-wrapper th {
  background-color: #f6f7fa;
}
.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}


.over-flow {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.columns {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
<style>
  .vul-table-tooltip {
  font-size: 14px;
  max-width:500px;
}
</style>
